package com.amita.ez.web;

import com.amita.ez.base.Const;
import com.amita.ez.entity.SysDept;
import com.amita.ez.service.ISysDeptService;
import com.amita.ez.util.ExcelUtils;
import com.amita.ez.vo.DeptVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/sysdept")
//@Tag(name = "账户信息表")
public class SysDeptCtrl {

    @Autowired
    Mapper mapper;

    @Autowired
    ISysDeptService sysDeptService;


    /**
     * queryWrapper
     * @param query
     * @return
     */
    private QueryWrapper<SysDept> getQueryWrapper(SysDept query, String sort) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
//        String deptNo = query.getDeptNo();
//        if(StringUtils.isNotBlank(deptNo)){
//            queryWrapper.eq("dept_no",deptNo);
//        }
//        String deptName = query.getDeptName();
//        if(StringUtils.isNotBlank(deptName)){
//            queryWrapper.like("dept_name", deptName);
//        }

//        queryWrapper.lambda().orderByAsc(SysDept::getRealclass);
        if(StringUtils.isNotBlank(sort)){
            sort = sort.replace(",asc", "");
            if(sort.endsWith(",desc")){
                queryWrapper.orderByDesc(sort.replace(",desc", ""));
            }else {
                queryWrapper.orderByAsc(sort);
            }
        }
        return queryWrapper;
    }



    /**
     * 查询全部 tree
     * @return
     */
    @GetMapping("/tree")
    public Object tree(){
        QueryWrapper<SysDept> wrapper = new QueryWrapper();
//        wrapper.lambda().eq(SysDept::getEnabled, true);
        List<SysDept> deptList = sysDeptService.list(wrapper);
        List<DeptVO> deptVOList = deptList.stream().map(el -> mapper.map(el, DeptVO.class)).collect(Collectors.toList());
        List<DeptVO> rootList = deptVOList.stream().filter(el -> el.getPid() == null).collect(Collectors.toList());
        List<DeptVO> otherList = deptVOList.stream().filter(el -> el.getPid() != null).collect(Collectors.toList());
        buildTree(rootList, otherList);

        return rootList;
    }

    private void buildTree(List<DeptVO> rootList, List<DeptVO> otherList) {
        if(rootList.isEmpty() || otherList.isEmpty()){
            return;
        }
        for (DeptVO root : rootList) {
            Long oid = root.getOid();
            List<DeptVO> children = otherList.stream().filter(el -> el.getPid() == oid).collect(Collectors.toList());
            root.setChildren(children);

            List<DeptVO> others = otherList.stream().filter(el -> el.getPid() != oid).collect(Collectors.toList());
            buildTree(children, others);
        }
    }

    /**
     * 查询全部 (最多返回 100条记录)
     * @return
     */
    @GetMapping("/all")
    public Object all(SysDept query, String sort){
        IPage<SysDept> pageCondition = new Page(1, 1000);
        QueryWrapper<SysDept> queryWrapper = getQueryWrapper(query, sort);
        IPage<SysDept> result = sysDeptService.page(pageCondition, queryWrapper);
        List<SysDept> records = result.getRecords();

        return records;
    }
    /**
     * 查询 分页
     * @param page
     * @param size
     * @return
     */
    @GetMapping()
    public Object find(@RequestParam(value = "page",defaultValue = "1")int page,
                       @RequestParam(value = "size",defaultValue = "10")int size,

                       SysDept query,String sort){
        IPage<SysDept> pageCondition = new Page(page, size);
        QueryWrapper<SysDept> queryWrapper = getQueryWrapper(query, sort);
        IPage<SysDept> result = sysDeptService.page(pageCondition, queryWrapper);
        return result;
    }



    @GetMapping("/{id}")
    public Object findOne(@PathVariable("id") String id){
        SysDept item = sysDeptService.getById(id);
        return item;
    }

    /**
     * 保存/更新
     * @param sysDept
     * @return
     */
    @PostMapping()
    public Object saveIt (SysDept sysDept){

        boolean flag = sysDeptService.saveOrUpdate(sysDept);
        Assert.isTrue(flag, Const.CRUD_FAIL_MSG);
        return R.ok("操作成功");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("/d")
    public void remove(String ids){
        boolean flag =  sysDeptService.removeByIds(Arrays.asList(ids.split(",")));
        Assert.isTrue(flag, Const.CRUD_FAIL_MSG);

    }


    /**
     * 导入
     * @param file
     * @return
     */
    @PostMapping("/import")
    public void doImport(MultipartFile file){

//        Assert.notNull(file, "id should not null");
//        if(file.isEmpty()){
//            throw new RuntimeException("file is empty");
//        }

    }

    /**
     * 导出
     * @param query
     */
    @GetMapping("/export")
    public void doExport(SysDept query, String sort, HttpServletResponse response) throws IOException {
        IPage pageCondition = new Page(1, 1000);
        QueryWrapper<SysDept> queryWrapper = getQueryWrapper(query, sort);
        IPage result = sysDeptService.page(pageCondition, queryWrapper);
        List records = result.getRecords();

        ExcelUtils.exportExcel(records, "SysDept表", null, SysDept.class, "SysDept", response);
    }

}
